﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;
using System.Data.SqlClient;
using System.Data;

public partial class login : System.Web.UI.Page
{
    string urlReferrer = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["txtLogout"] == "1")
        {
            //this.RegisterStartupScript("islogout", "logout");
            RecordLogOut(Session["logID"].ToString());
            //Session.Clear();
            //Session.RemoveAll();
            //Session.Abandon();
        }
        else if (User.Identity.IsAuthenticated)
        {
            Response.Redirect("Main/Default.aspx");
        }

        if (Request["urlReferrer"] != null)
        {
            urlReferrer = Request["urlReferrer"];
        }

        if (!IsPostBack)
        {
            LoadLoginCookie();
        }
    }

    private void LoadLoginCookie()
    {
        
        if (Request.Cookies["OfficeOnlineUserLogin"] != null)
        {

            txtUserName.Text = Request.Cookies["OfficeOnlineUserLogin"]["userName"];
            txtPassword.Text = Request.Cookies["OfficeOnlineUserLogin"]["password"];
            chkRememberUser.Checked = true;
            //btnLogin_Click(null, null);
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {        
        int value = CommitLogin(txtUserName.Text, txtPassword.Text);
        switch(value)
        {
            case 0:
                trResponse.Visible = true;
                lblResponse.Text = "User Doesn't Exist";
                break;
            case -1:
                trResponse.Visible = true;
                lblResponse.Text = "Incorrect Password";
                break;
            case 1:
                trResponse.Visible = false;
                lblResponse.Text = "";
                ProcceedToLogin();
                break;
        }
        
    }

    private void ProcceedToLogin()
    {
        if (chkRememberUser.Checked == true)
        {
            HttpCookie userLogin = new HttpCookie("OfficeOnlineUserLogin");
            userLogin.Expires = DateTime.Now.AddDays(7);
            userLogin.Values.Add("userName", txtUserName.Text);
            userLogin.Values.Add("password", txtPassword.Text);
            Response.Cookies.Add(userLogin);
        }

        GenerateSession(txtUserName.Text);
        int logID = RecordLogIn(txtUserName.Text);
        Session.Add("logID", logID);

        if (Session["CurrentUser"] != null)
        {
            if (urlReferrer == "")
            {
                Response.Redirect("./Main");
            }
            else
            {
                Response.Redirect(urlReferrer);
            }
        }
    }
    
    private void GenerateSession(string userName)
    {
        string command = "sp_tb_user_GetUserInfo";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
        
        sqlCmd.Parameters.Add(new SqlParameter("@userName", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@userType", SqlDbType.Int, 32,""));
        sqlCmd.Parameters.Add(new SqlParameter("@userRealName", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@userEmailAddress", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@userAddress", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@userContactNumber", SqlDbType.NVarChar, 255, ""));
                
        sqlCmd.Parameters["@userName"].Value = userName;
        sqlCmd.Parameters["@userType"].Direction = ParameterDirection.Output;
        sqlCmd.Parameters["@userRealName"].Direction = ParameterDirection.Output;
        sqlCmd.Parameters["@userEmailAddress"].Direction = ParameterDirection.Output;
        sqlCmd.Parameters["@userAddress"].Direction = ParameterDirection.Output;
        sqlCmd.Parameters["@userContactNumber"].Direction = ParameterDirection.Output;

        sqlCmd.ExecuteNonQuery();

        int userType = Convert.ToInt16(sqlCmd.Parameters["@userType"].Value);
        string userRealName = sqlCmd.Parameters["@userRealName"].Value.ToString();
        string userEmailAddress = sqlCmd.Parameters["@userEmailAddress"].Value.ToString();
        


        OfficeOnlineUser currentUser = new OfficeOnlineUser(userName, userType, userRealName,userEmailAddress);
        Session.Timeout = 30;
        Session.Add("CurrentUser", currentUser);
        //some debugging codes
        //this.RegisterStartupScript("utype", "userType=" + sqlCmd.Parameters["@userType"].Value + "<br/>");
        //this.RegisterStartupScript("uAddress", "userAddress=" + sqlCmd.Parameters["@userAddress"].Value + "<br/>");
        //this.RegisterStartupScript("uContact", "userContactNumber=" + sqlCmd.Parameters["@userContactNumber"].Value + "<br/>");
    }    

    private int CommitLogin(string userName, string password)
    {
        
        string command = "sp_tb_user_AllowUserLogin";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCmd.Parameters.Add(new SqlParameter("@userName", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@password", SqlDbType.NVarChar, 32, ""));

        sqlCmd.Parameters["@userName"].Value = userName;
        sqlCmd.Parameters["@password"].Value = DatabaseFunctions.MD5Encode(password);


        int value = 0;
        
        try{
            value = Convert.ToInt16(sqlCmd.ExecuteScalar().ToString());
        }catch(Exception ex)
        {   
           value = 0;  
        }

        sqlCon.Close();

        return value;
    }

    private int RecordLogIn(String userName)
    {
        string command = "sp_tb_user_log_RecordLogIn";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCmd.Parameters.Add(new SqlParameter("@userID", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@result", SqlDbType.Int, 32, ""));
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@userID"].Value = userName;
        
        sqlCmd.ExecuteNonQuery();

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
        }
        catch (Exception ex)
        {
            result = 0;
        }

        sqlCon.Close();

        return result;
    }

    private int RecordLogOut(String logID)
    {
        string command = "sp_tb_user_log_RecordLogOut";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCmd.Parameters.Add(new SqlParameter("@logID", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@result", SqlDbType.Int, 32, ""));
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@logID"].Value = logID;

        sqlCmd.ExecuteNonQuery();

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
        }
        catch (Exception ex)
        {
            result = 0;
        }

        sqlCon.Close();

        return result;
    }    
}
